/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.googlecode.jsimplemarket.wicket.pages;

//import com.googlecode.jmicroerp.repository.GenericRestriction;
import com.googlecode.jsimplemarket.model.Creanta;
import com.googlecode.jsimplemarket.model.Firma;
import com.googlecode.jsimplemarket.model.Inchiriere;
import com.googlecode.jsimplemarket.model.NTipTaxa;
import com.googlecode.jsimplemarket.model.Plata;
import com.googlecode.jsimplemarket.model.SpatiuComercial;
import com.googlecode.jsimplemarket.model.Taxa;
import com.googlecode.jsimplemarket.repository.GenericOrder;
import com.googlecode.jsimplemarket.repository.GenericProperty;
import com.googlecode.jsimplemarket.repository.GenericRestriction;
import com.googlecode.jsimplemarket.service.GenericService;
import com.googlecode.jsimplemarket.service.InchiriereService;
import com.googlecode.jsimplemarket.service.TaxaService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.extensions.markup.html.form.DateTextField;
import org.apache.wicket.extensions.yui.calendar.DatePicker;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

/**
 *
 * @author Alexandru.Codescu
 */
public class PlataAnticipataPage extends DefaultPageTemplate {

    @SpringBean(name = "genericService")
    private GenericService<Firma> serviceFirma;
    @SpringBean(name = "genericService")
    private GenericService<NTipTaxa> serviceTipTaxa;
    @SpringBean(name = "genericService")
    private GenericService<Taxa> serviceTaxa;
    @SpringBean(name = "genericService")
    private GenericService<SpatiuComercial> spatiuComercialService;
    @SpringBean(name = "genericService")
    private GenericService<Plata> plataService;
    @SpringBean(name = "genericService")
    private GenericService<Creanta> creantaService;
    @SpringBean(name = "taxaService")
    private TaxaService taxaService;
    @SpringBean(name = "genericService")
    private GenericService<Inchiriere> inchiriereService;
    @SpringBean(name = "inchiriereService")
    private InchiriereService serviceInchiriere;
    @SpringBean(name = "genericService")
    private GenericService<Firma> firmaService;    
    //@SpringBean(name = "genericService")
    //private GenericService<NStareSpatiuComercial> serviceStareSpatiu;
    
    private Firma firma1; //existenta pt select
    private Firma firma; //new
    private SpatiuComercial spatiu;
    //private NStareSpatiuComercial stare;
    private Date dataPlata = new Date();
    private Date dataStart = getFirstDayOfMonth();
    private Date dataStop = getLastDayOfMonth();
    private Locale locale = new Locale("ro","RO");
    private Long firmaId;
    private Taxa taxa1;
    private String valoare;
    
    private Date getDataSfarsit(Date dataInceput, int interval) {
        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.setTime(dataInceput);
        gregorianCalendar.add(GregorianCalendar.DATE, interval);
        
        return gregorianCalendar.getTime();
    }
    
    private Date getDataInceputZi(Date data) {
        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.setTime(data);
        gregorianCalendar.set(GregorianCalendar.HOUR, 0);
        gregorianCalendar.set(GregorianCalendar.MINUTE, 0);
        gregorianCalendar.set(GregorianCalendar.SECOND, 0);
        gregorianCalendar.set(GregorianCalendar.AM_PM, GregorianCalendar.AM);
        return gregorianCalendar.getTime();
    }
    
    private Date getDataSfarsitZi(Date data) {
        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.setTime(data);
        gregorianCalendar.set(GregorianCalendar.AM_PM, GregorianCalendar.PM);
        gregorianCalendar.set(GregorianCalendar.HOUR, 11);
        gregorianCalendar.set(GregorianCalendar.MINUTE, 59);
        gregorianCalendar.set(GregorianCalendar.SECOND, 59);
        return gregorianCalendar.getTime();
    }
    
    private GregorianCalendar getTodayCalendar() {
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.set(GregorianCalendar.HOUR_OF_DAY, 0);
        calendar.set(GregorianCalendar.MINUTE, 0);
        calendar.set(GregorianCalendar.SECOND, 0);
        //calendar.set(GregorianCalendar.AM_PM, GregorianCalendar.AM);
        calendar.set(GregorianCalendar.MILLISECOND, 0);
        return calendar;
    }
    
    private Date getTodayDate() {
        return getTodayCalendar().getTime();
    }
    
    private Date addDays(Date date, int days) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.add(Calendar.DATE, days);
                 
        return cal.getTime();
    }
    
    private Date get7DayDate() {
        GregorianCalendar calendar = getTodayCalendar();
        calendar.add(GregorianCalendar.DATE, -7);
        
        return calendar.getTime();
    }
    
    private Date getFirstDayOfMonth() {
        GregorianCalendar calendar = getTodayCalendar();
        //comment next line for current month
        calendar.add(GregorianCalendar.MONTH, 1);
        calendar.set(GregorianCalendar.DATE, 1); //first day of the next month
        
        return calendar.getTime();
    }
    
    private Date getLastDayOfMonth() {
        GregorianCalendar calendar = getTodayCalendar();
      //comment next line for current month
        calendar.add(GregorianCalendar.MONTH, 1);
        calendar.set(GregorianCalendar.DATE, 
        		calendar.getActualMaximum(GregorianCalendar.DAY_OF_MONTH)); //last day of the next month
        
        return calendar.getTime();
    }
    
    public PlataAnticipataPage(Long idSpatiu) {
    	
    	Object[] sc = serviceInchiriere.queryFirmaByTaraba(idSpatiu, new Date());
    	firmaId = (sc == null ? (1L) : (Long) sc[3]);    	
    	firma1 = serviceFirma.getById(Firma.class, firmaId);
        firma = new Firma();
        spatiu = spatiuComercialService.getById(SpatiuComercial.class, idSpatiu);
        //stare = serviceStareSpatiu.getById(NStareSpatiuComercial.class, 5L); //3L-Rezervat; 5-AI
        
        taxa1 = taxaService.findByCod("T_ANTP");
        //taxa1 = serviceTaxa.getById(Taxa.class, 2L);
        valoare = taxa1.getValoare().toString();
        init();
    }
    
    public PlataAnticipataPage(Long idSpatiu, Long idFirma) {
    	
    	firma1 = serviceFirma.getById(Firma.class, idFirma);
        firma = new Firma();
        spatiu = spatiuComercialService.getById(SpatiuComercial.class, idSpatiu);
        //stare = serviceStareSpatiu.getById(NStareSpatiuComercial.class, 5L); //3L-Rezervat; 5-AI
        
        taxa1 = taxaService.findByCod("T_ANTP");
        //taxa1 = serviceTaxa.getById(Taxa.class, 2L);
        valoare = taxa1.getValoare().toString();
        init();
    }
    
    private void init() {
    	Label lblTaraba = new Label("codTaraba", spatiu.getCod());
    	add(lblTaraba);
    	final DropDownChoice<Taxa> ddcTaxa = new DropDownChoice<Taxa>(
                "taxa1", 
                new PropertyModel<Taxa>(this, "taxa1"),
                new LoadableDetachableModel<List<Taxa>>() {
                    @Override
                    protected List<Taxa> load() {
                    	
                    	//List<GenericOrder> taxeOrder = new ArrayList<GenericOrder>();
                    	//taxeOrder.add(new GenericOrder(new GenericProperty("valoare")));
                    	
                    	//List<GenericRestriction> resAct = new ArrayList<GenericRestriction>();
                    	//resAct.add(new GenericRestriction(new GenericProperty("id"),2));
                    	
                    	Integer[] intArray = new Integer[] { 2, 3, 6 }; // AI-700, R-300, AA-350
                    	ArrayList<Integer> intList = new ArrayList<Integer>(Arrays.asList(intArray));
                    	
                    	GenericRestriction resAI = new GenericRestriction(new GenericProperty("id"), intList);
                        return serviceTaxa.getList(Taxa.class, Arrays.asList(resAI), null);
             
                    }
                }, 
                new ChoiceRenderer<Taxa>("denumire", "id")
        );
    	
    	
    	
    	final DropDownChoice<Firma> ddcFirma = new DropDownChoice<Firma>(
                "firma1", 
                new PropertyModel<Firma>(this, "firma1"),
                new LoadableDetachableModel<List<Firma>>() {
                    @Override
                    protected List<Firma> load() {
                    	
                    	List<GenericOrder> firmaOrder = new ArrayList<GenericOrder>();
                   	    firmaOrder.add(new GenericOrder(new GenericProperty("denumire"), true));
                   	 
                        return firmaService.getList(Firma.class, null, firmaOrder);
             
                    }
                }, 
                new ChoiceRenderer<Firma>("denumire", "id")
        );
    	
    	final TextField<String> tfValoare = new TextField<String>("valoare", new PropertyModel<String>(this, "valoare"));
    	tfValoare.setOutputMarkupId(true);
    	
    	final DateTextField tfDataPlata = new DateTextField("dataPlata", new PropertyModel<Date>(this, "dataPlata"), "dd.MM.yyyy");
        tfDataPlata.add(new DatePicker());        

        final DateTextField tfDataStart = new DateTextField("dataStart", new PropertyModel<Date>(this, "dataStart"), "dd.MM.yyyy");
        tfDataStart.add(new DatePicker());
        
        final DateTextField tfDataStop = new DateTextField("dataStop", new PropertyModel<Date>(this, "dataStop"), "dd.MM.yyyy");
        tfDataStop.add(new DatePicker());
        
        FeedbackPanel feedback = new FeedbackPanel("feedback");
        add(feedback);
        
	    Form<?> form1 = new Form<Void>("form1");
	    form1.add(ddcTaxa, tfValoare, ddcFirma, tfDataPlata, tfDataStart, tfDataStop);
	    
		ddcTaxa.add(new AjaxFormComponentUpdatingBehavior("onchange"){
		    		
				@Override
				protected void onUpdate(AjaxRequestTarget target)
				{
				    //valoare = taxa1.getValoare().toString();
				    tfValoare.setDefaultModelObject(taxa1.getValoare().toString());
				    tfValoare.modelChanged();
					target.add(tfValoare);
				}
		});
	    
	    form1.add(new SubmitLink("submit1") {
	    @Override
	    public void onSubmit() {
	                        
	        	//Taxa taxa = taxaService.findByCod("T_ANTP");
	            Inchiriere inchiriere = new Inchiriere();
	            inchiriere.setFirma(firma1);
	            inchiriere.setDataInceput(dataStart);
	            inchiriere.setDataSfarsit(dataStop);
	            inchiriere.setSpatiuComercial(spatiu);
	            inchiriere.setTaxe(new ArrayList<Taxa>());
	            inchiriere.getTaxe().add(taxa1);
	            inchiriereService.insert(inchiriere);
	            
	            //spatiu.setStareSpatiuComercial(stare);
	            spatiuComercialService.update(spatiu);
	            
	            Creanta creanta = new Creanta();
	            creanta.setDataInceput(inchiriere.getDataInceput());
	            creanta.setDataSfarsit(getDataSfarsit(creanta.getDataInceput(), 7));
	            creanta.setTaxa(taxa1);
	            creanta.setValoare(taxa1.getValoare());
	            creanta.setValoareReziduala(BigDecimal.ZERO);
	            creanta.setPlati(new ArrayList<Plata>());
	            creanta.setInchiriere(inchiriere);
	            creantaService.insert(creanta);
	            
	            Plata plata = new Plata();
	            plata.setDataPlata(dataPlata);
	            plata.setValoare(taxa1.getValoare());
	            plata.setCreanta(creanta);
	            plataService.insert(plata);
	            setResponsePage(new PiataViewPage());
	        }
	 	
	   });
	   
	    form1.add(new Link("quit") {
	       
	        @Override
	        public void onClick() {
	            setResponsePage(new PiataViewPage());
	        }
	       
	    });
	   
	    add(form1);
    	
        Form<Firma> form = new Form<Firma>("form");
        form.setModel(new CompoundPropertyModel<Firma>(firma));
        
        TextField<String> tfDenumire = new TextField<String>("denumire");
        tfDenumire.setRequired(true);
        form.add(tfDenumire);
        
        TextField<String> tfCif = new TextField<String>("cif");
        tfCif.setRequired(true);
        form.add(tfCif);
        
        TextArea<String> taAdresa = new TextArea<String>("sediuSocial");
        form.add(taAdresa);
        
        TextField<String> tfDateContact = new TextField<String>("dateContact");
        tfDateContact.setRequired(true);
        form.add(tfDateContact);
        
        form.add(new SubmitLink("submit") {
            
            @Override
            public void onSubmit() {
                firmaService.insert(firma);
                
//                Taxa taxa = taxaService.findByCod("T_ANTP");
//                Inchiriere inchiriere = new Inchiriere();
//                inchiriere.setFirma(firma);
//                inchiriere.setDataInceput(dataStart);
//                inchiriere.setDataSfarsit(dataStop);
//                inchiriere.setSpatiuComercial(spatiu);
//                inchiriere.setTaxe(new ArrayList<Taxa>());
//                inchiriere.getTaxe().add(taxa);
//                inchiriereService.insert(inchiriere);
                
                //spatiu.setStareSpatiuComercial(stare);
//                spatiuComercialService.update(spatiu);
                
//                Creanta creanta = new Creanta();
//                creanta.setDataInceput(inchiriere.getDataInceput());
//                creanta.setDataSfarsit(getDataSfarsit(creanta.getDataInceput(), 7));
//                creanta.setTaxa(taxa);
//                creanta.setValoare(taxa.getValoare());
//                creanta.setValoareReziduala(BigDecimal.ZERO);
//                creanta.setPlati(new ArrayList<Plata>());
//                creanta.setInchiriere(inchiriere);
//                creantaService.insert(creanta);
                
//                Plata plata = new Plata();
//                plata.setDataPlata(dataPlata);
//                plata.setValoare(taxa.getValoare());
//                plata.setCreanta(creanta);
//                plataService.insert(plata);
                info("A fost introdus cu succes clientul "+firma.getDenumire()+" .<br>"
                		+ "Continua cu configurare platii.");
                setResponsePage(new PlataAnticipataPage(spatiu.getId(), firma.getId()));
            }
            
        });
        
        form.add(new Link("renuntare") {
            
            @Override
            public void onClick() {
                setResponsePage(new PiataViewPage());
            }
            
        });
        
        add(form);
    }
    
}
